package com.tsunami.user.resolver;

import com.tsunami.context.BaseContextHandler;
import com.tsunami.user.annotation.LoginUser;
import com.tsunami.user.feign.UserResolveApi;
import com.tsunami.user.model.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @Classname ContextArgumentResolver
 * @Description TODO
 * @Date 2021-11-02 16:59
 * @Created by lx
 */
@Slf4j
public class ContextArgumentResolver implements HandlerMethodArgumentResolver {

    private UserResolveApi userResolveApi;

    public ContextArgumentResolver(UserResolveApi userResolveApi) {
        this.userResolveApi = userResolveApi;
    }

    @Override
    public boolean supportsParameter(MethodParameter mp) {
        return mp.hasParameterAnnotation(LoginUser.class)
                && mp.getParameterType().equals(SysUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter mp,
                                  ModelAndViewContainer mvc,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        Long userId = BaseContextHandler.getUserId();
        String account = BaseContextHandler.getAccount();
//        String name = BaseContextHandler.getName();
//        Long orgId = BaseContextHandler.getOrgId();
        String clientId = BaseContextHandler.getClientId();

        SysUser user = SysUser.builder()
                .id(userId)
                .account(account)
//                .name(name)
//                .orgId(orgId)
                .clientId(clientId)
                .build();
        try {
            LoginUser loginUser = mp.getParameterAnnotation(LoginUser.class);
            boolean isFull = loginUser.isFull();

            if (isFull || loginUser.isStation() || loginUser.isOrg() || loginUser.isRoles()) {
//                R result = userResolveApi.getById(Long.valueOf(userId),
//                        UserQuery.builder()
//                                .full(isFull)
//                                .org(loginUser.isOrg())
//                                .station(loginUser.isStation())
//                                .roles(loginUser.isRoles())
//                                .build());
//                if (result.getExtra()!=null) {
//                    return result.getExtra();
//                }
            }
        } catch (Exception e) {
            log.warn("注入登录人信息时，发生异常. --> {}", user, e);
        }
        return user;

    }
}
